package org.dei.perla.rockfall.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dei.perla.utils.logger.SimpleLogger;
import org.dei.perla.utils.messages.AdapterFpcMessage;
import org.dei.perla.utils.pipe.Pipe;
import org.dei.perla.utils.pipe.PipePair;
import org.dei.perla.utils.waiter.Waitable;
import org.dei.perla.utils.waiter.Waiter;

public class DSPicDataDumper {
	
	private Waiter<Pipe<AdapterFpcMessage>> pipeInWaiter;
	private String path;
	
	public DSPicDataDumper(PipePair<AdapterFpcMessage, AdapterFpcMessage> pipePair, String path) {
		
		pipeInWaiter = new Waiter<Pipe<AdapterFpcMessage>>();
		pipeInWaiter.start();
		pipeInWaiter.addWaitable(pipePair.getInPipe().getWaitable());
		
		this.path = path;
		
		Thread thread = new Thread(new PipeInWaiterThread());
		thread.start();
	}
	
	private class PipeInWaiterThread implements Runnable {
		
		private void saveToFile(byte[] payload) {
			try {
				File file = new File(path);
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				
				for (byte b : payload) {
					bos.write(b);
				}
				
				bos.close();
				fos.close();
			} catch (FileNotFoundException e) {
				SimpleLogger.log(this.getClass(), e.getMessage());
		 	} catch (IOException e) {
		 		SimpleLogger.log(this.getClass(), e.getMessage());
			}
		}
		
		public void run() {
			Waitable<Pipe<AdapterFpcMessage>> waitable;
			AdapterFpcMessage adapterFpcMessage;
			
			
			while(true) {
				waitable = pipeInWaiter.waitNext();
				adapterFpcMessage = waitable.getParentComponent().dequeue();
				
				if (adapterFpcMessage != null) {
					saveToFile(adapterFpcMessage.getPayload());
				} else {
					waitable.getParentComponent().stop();
					pipeInWaiter.removeWaitable(waitable);
					pipeInWaiter.stop();
					break;
				}
			}
			SimpleLogger.log(this.getClass(), "Stopped " + path);
		}
	}
}
